package com.example.felord.oauth2_1samples.wechat;

import com.google.common.collect.Maps;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.Assert;

import java.util.Map;

/**
 * custom wechat authorization request
 */
public class WechatOAuth2AuthorizationRequestCustomizer {

    private final static String WECHAT_CLIENT_ID_NAME = "appid";
    private final static String WECHAT_FRAGMENT = "wechat_redirect";
    private final String registrationId;


    public WechatOAuth2AuthorizationRequestCustomizer(String registrationId) {
        Assert.notNull(registrationId, "wechat registration id must not be null");
        this.registrationId = registrationId;
    }

    /**
     * customize wechat oauth2 request, the main logic is to replace CLIENT_ID with APPID
     * @param builder OAuth2AuthorizationRequest.Builder
     */
    public void customize(OAuth2AuthorizationRequest.Builder builder){
        builder.attributes(attributes -> {
            String registrationId = (String) attributes.get(OAuth2ParameterNames.REGISTRATION_ID);
            if(this.registrationId.equals(registrationId)){
                builder.parameters((parameters) -> {
                    Map<String,Object> linkedParameters = Maps.newLinkedHashMap();
                    parameters.forEach((key,value) -> {
                        if(OAuth2ParameterNames.CLIENT_ID.equals(key)){
                            linkedParameters.put(WECHAT_CLIENT_ID_NAME, value);
                        }else {
                            linkedParameters.put(key,value);
                        }
                    });
                    parameters.clear();
                    parameters.putAll(linkedParameters);
                });
                builder.authorizationRequestUri((uriBuilder) -> uriBuilder.fragment(WECHAT_FRAGMENT).build());
            }
        });
    }
}
